
/**
 * WebSocket工具
 */

import { ElMessage } from 'element-plus'
import { formatToken, getToken } from '../auth';

let websocket: WebSocket | null = null; // 用于存储实例化后websocket
let rec: any; // 断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let timer: any; // 心跳
// 创建websocket
function creatWebSocket(wsUrl: string, onmessage = websocketonmessage, onerror = (e) => { }, onclose = websocketclose) {
    // console.log("websocket==================");
    // 判断当前浏览器是否支持WebSocket
    if ("WebSocket" in window) {
        // console.log("当前浏览器支持 WebSocket");
    } else if ("MozWebSocket" in window) {
        console.log("当前浏览器支持 MozWebSocket");
    } else {
        console.log("当前浏览器不支持 WebSocket");
    }


    try {
        return initWebSocket(wsUrl, onmessage, onerror, onclose); // 初始化websocket连接
    } catch (e) {
        // console.log("尝试创建连接失败");
        return reConnect(wsUrl, onmessage, onerror, onclose); // 如果无法连接上 webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
    }
}
// 初始化websocket
function initWebSocket(wsUrl: string, onmessage = websocketonmessage, onerror = (e) => { }, onclose = websocketclose) {
    websocket = new WebSocket(wsUrl);
    websocket.onopen = function () {
        websocketOpen();
        timer = setInterval(function () { //每隔5秒钟发送一次心跳，避免websocket连接因超时而自动断开
            var ping = { "type": "ping" };
            websocket.send(JSON.stringify(ping));
        }, 5000);
    };


    // 接收
    websocket.onmessage = function (e: MessageEvent<any>) {
        onmessage(e);
    };


    // 连接发生错误
    websocket.onerror = function (e) {
        // console.log("WebSocket连接发生错误");
        onerror(e)
    };


    websocket.onclose = function (e) {
        onclose(e);
        timer && clearInterval(timer);
    };

    return websocket
}
// 定义重连函数
let reConnect = (wsUrl: string, onmessage = websocketonmessage, onerror = (e) => { }, onclose = websocketclose) => {
    console.log("尝试重新连接");
    if (websocket) return websocket; // 如果已经连上就不在重连了
    rec && clearTimeout(rec);
    rec = setTimeout(function () {
        // 延迟5秒重连  避免过多次过频繁请求重连
        creatWebSocket(wsUrl, onmessage, onerror, onclose);
    }, 5000);
};
// 创建连接
function websocketOpen() {
    console.log("连接成功");
}
// 数据接收
function websocketonmessage(e: MessageEvent<any>) {
    console.log("数据接收", e.data);

}
// 关闭
function websocketclose(e: any) {
    console.log(e);
    console.log("connection closed (" + e.code + ")");
}
// 数据发送
function websocketsend(data: any) {
    console.log("发送的数据", data, JSON.stringify(data));
    if (websocket) { // 检查连接状态
        websocket.send(JSON.stringify(data));
    } else {
        ElMessage({
            showClose: true,
            message: "请先连接websocket",
            type: 'error',
        })
    }
}
// 发送
function sendWebSocket(data: any) {

    websocketsend(data);
    console.log("------------------");
}
// 关闭
let closeWebSocket = () => {
    if (websocket) {
        websocket.close();
        // ElMessage({
        //     showClose: true,
        //     message: "webSocket已关闭",
        //     type: 'success',
        // })
    }
};
export {
    initWebSocket,
    sendWebSocket,
    creatWebSocket,
    closeWebSocket,
};
